snippet qt_log "qt log"
#include <QtGlobal>
#include <QtDebug>
#include <QTextStream>
#include <QTextCodec>
#include <QLocale>
#include <QTime>
#include <QFile>

const QString logFilePath = "debug.log";
bool          logToFile   = false;

void customMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QHash<QtMsgType, QString> msgLevelHash({{QtDebugMsg, "Debug"}, {QtInfoMsg, "Info"}, {QtWarningMsg, "Warning"}, {QtCriticalMsg, "Critical"}, {QtFatalMsg, "Fatal"}});
    QByteArray                localMsg         = msg.toLocal8Bit();
    QTime                     time             = QTime::currentTime();
    QString                   formattedTime    = time.toString("hh:mm:ss.zzz");
    QByteArray                formattedTimeMsg = formattedTime.toLocal8Bit();
    QString                   logLevelName     = msgLevelHash[type];
    QByteArray                logLevelMsg      = logLevelName.toLocal8Bit();

    if(logToFile)
    {
        QString txt = QString("%1 %2: %3 (%4)").arg(formattedTime, logLevelName, msg, context.file);
        QFile   outFile(logFilePath);
        outFile.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream ts(&outFile);
        ts << txt << endl;
        outFile.close();
    }
    fprintf(stderr, "%s %s: %s (%s:%u, %s)\n", formattedTimeMsg.constData(), logLevelMsg.constData(), localMsg.constData(), context.file, context.line, context.function);
    fflush(stderr);

    if(type == QtFatalMsg)
        abort();
}
// qInstallMessageHandler(customMessageOutput);
endsnippet

snippet qt_timer "user QTimer" b
QTimer *${1:timer} = new QTimer(this);
connect($1, SIGNAL(timeout()), this, SLOT(${2:onTimeout}()));
$1->setsetSingleShot(false);
$1->setInterval(1000);
$1.start();
endsnippet

snippet qt_delay "delay by QEventloop" b
QEventLoop eventloop;
QTimer::singleShot(${1:delayTime(msec)}, &eventloop, &QEventLoop::quit);
eventloop.exec();
endsnippet


snippet qt_thread_create "moveToThread"
#ifndef $1_H
#define $1_H

#include <QCoreApplication>
#include <QDebug>
#include <QThread>
#include <QObject>

class ${1:Name} : public QObject
{
    Q_OBJECT
public:
    explicit $1(QObject *parent = 0);
    ~$1();

signals:
    void sig_finish();  // 无参数信号

public slots:
    void slot_dowork();
};
#endif
endsnippet


snippet qt_thread_usage "thread use template"
QThread* thread = new QThread( );
Task* task      = new Task();

task->moveToThread(thread);

connect(thread, SIGNAL(started()), task, SLOT(doWork()));
connect(task, SIGNAL(workFinished()), thread, SLOT(quit()));

connect(task, SIGNAL(workFinished()), task, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

thread->start();
endsnippet
